package com.xutianpeng.disk.spring.security;

import com.xutianpeng.disk.mybatis.entity.PtUserEntity;
import com.xutianpeng.disk.user.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 获取当前登录用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();

        // 查询用户UUID
        PtUserEntity user = userService.queryUserByUsername(username);
        if (user != null && userService.needResetPassword(user.getUserUuid())) {
            // 需要重置密码，跳转到重置页面
            request.getSession().setAttribute("needResetUserId", user.getUserUuid());
            response.sendRedirect(request.getContextPath() + "/login/resetPwd");
        } else {
            // 正常登录，跳转到首页
            response.sendRedirect(request.getContextPath() + "/login/main");
        }
    }
}